/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.data.crud;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author WStrafacce
 */
public class CrudAdministrador {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("wabtPU");

    public void persist(Object object) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }
    
    public java.util.Collection<br.data.model.Admin> getAll() {
        EntityManager em = emf.createEntityManager();
        try {
            return em.createNamedQuery("Administradores.findAll").getResultList();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            //em.getTransaction().rollback();
            return null;
        } finally {
            em.close();
        }
    }
    
    public br.data.model.Admin getAdministrador(int codigo) {

        EntityManager em = emf.createEntityManager();
        try {
            return em.find(br.data.model.Admin.class, codigo);
        } catch (Exception e) {
            return null;
        } finally {
            em.close();
        }
    }
    
    public br.data.model.Admin getAdministrador(String login) {

        EntityManager em = emf.createEntityManager();
        try {
            return (br.data.model.Admin) em.createNamedQuery("Administradores.findByLogin").setParameter("login", login).getSingleResult();
        } catch (Exception e) {
            return null;
        } finally {
            em.close();
        }
    }
    
    public br.data.model.Admin getAdministrador(String login, String senha) {

        EntityManager em = emf.createEntityManager();
        try {
            return (br.data.model.Admin) em.createQuery("SELECT a FROM Admin a WHERE a.login = :login AND a.senha = :senha")
                                                            .setParameter("login", login)
                                                            .setParameter("senha", senha)
                                                            .getSingleResult();
        } catch (Exception e) {
            return null;
        } finally {
            em.close();
        }
    }
    
    
}
